package com.xnew.userOrg.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xnew.bean.common.SysOrgUserInfo;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.bean.common.T10MemOrgLinkmanInfo;
import com.xnew.constant.Constant;
import com.xnew.encrypt.Sm3Encrypt;
import com.xnew.bean.common.AuUserRole;
import com.xnew.entity.memberArchives.MemLinkmanInfo;
import com.xnew.entity.ssoApi.AccountVo;
import com.xnew.entity.ssoApi.PlatformOrgRegVo;
import com.xnew.entity.ssoApi.ResultDo;
import com.xnew.exception.CustomException;
import com.xnew.role.mapper.AuUserRoleMapper;
import com.xnew.ssoApi.mapper.SysUserInfoMapper;
import com.xnew.ssoApi.service.SsoApiService;
import com.xnew.sysOrgUser.mapper.T10MemOrgLinkmanInfoMapper;
import com.xnew.user.mapper.AuUserMapper;
import com.xnew.userOrg.mapper.SysOrgUserMapper;
import com.xnew.userOrg.service.SysOrgInfoService;
import com.xnew.utils.*;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class SysOrgInfoServiceImpl implements SysOrgInfoService {

    @Resource
    private SysOrgUserMapper sysOrgUserMapper;

    @Resource
    private AuUserRoleMapper auUserRoleMapper;

    @Resource
    private AuUserMapper auUserMapper;

    @Resource
    private T10MemOrgLinkmanInfoMapper memOrgLinkmanInfoMapperm;
    @Resource
    private SysUserInfoMapper sysUserInfoMapper;
    @Resource
    private SsoApiService ssoApiService;
    @Resource
    private SysUserInfoMapper t61SysUserInfoMapper;
    @Value("${SSO.subSystem1}")
    private String subSystem1 ; //	会员系统编号
    @Value("${SSO.subSystem2}")
    private String subSystem2 ; //	会员系统编号
    @Value("${SSO.Client_id}")
    private String Client_id ; //	系统编号
    private String access_token = "DF051D173D2A08F5AABFCB6C6D7878A0D6535456F4F519FC0D091DBCEF6BBA8F" ; //

    /**
     * 删除机构用户
     * @param orgId
     */
    @Override
    public void delSysOrgUser(String  orgId) {
        sysOrgUserMapper.deleteById(orgId);
        auUserMapper.deleteByPerUserNo(orgId);
        auUserRoleMapper.deleteByAuId(orgId);
    }

    @Override
    public void delSysOrgUser(String userInfoNo,String orgId) {
        auUserRoleMapper.deleteByUserInfoNo(userInfoNo);
        sysOrgUserMapper.deleteById(orgId);
        sysUserInfoMapper.deleteById(userInfoNo);
    }
    @Override
    public void updateSysOrgUserStatus(String orgId,String status) {
        String org_status_code; //机构状态,01正常 02注销
        if(status.equals("0")){
            org_status_code = "01";
        }else{
            org_status_code = "02";
        }
        sysOrgUserMapper.updataByStatus(orgId,org_status_code);
        sysUserInfoMapper.updataOrgByStatus(orgId,status);
    }
    /**
     * 新增机构用户
     * @param orgUser
     * @param userInfo
     * @return
     * @throws Exception
     */
    @Override
    public DataOutput insertOrgUser(SysOrgUserInfo orgUser, SysUserInfo userInfo, HttpServletRequest request) throws Exception {
        DataOutput out = DataOutput.success();
        List<SysUserInfo> sysUserInfos = auUserMapper.selectByLoginName(orgUser.getLoginName());
        if (sysUserInfos.size()>0){
            out.setCode(-90001);
            out.setMsg("保存失败，登录名已存在！");
            return out;
        }
        SysOrgUserInfo sysOrgUserInfo = null;
        System.out.println("=====判断机构代码（" + orgUser.getOrgCode() + "）是否存在==========");
        sysOrgUserInfo = sysOrgUserMapper.selectOrgByOrgCode("",orgUser.getOrgCode());
        if (sysOrgUserInfo != null) {
            out.setCode(-90001);
            out.setMsg("保存失败，机构代码已存在，请重新输入！");
            return out;
        }
        System.out.println("=====判断统一社会信用代码（" + orgUser.getAoiOrgNo() + "）是否存在==========");
        sysOrgUserInfo = sysOrgUserMapper.selectOrgByAoiOrgNo("",orgUser.getAoiOrgNo());
        if (sysOrgUserInfo != null) {
            out.setCode(-90001);
            out.setMsg("保存失败，统一社会信用代码已存在，请重新输入！");
            return out;
        }
        System.out.println("=====判断会员证书号码（" + orgUser.getOrgCertifNo() + "）是否存在==========");
        sysOrgUserInfo = sysOrgUserMapper.selectOrgByOrgCertifNo("",orgUser.getOrgCertifNo());
        if (sysOrgUserInfo != null) {
            out.setCode(-90001);
            out.setMsg("保存失败，会员证书号码已存在，请重新输入！");
            return out;
        }
        orgUser.setOrgId(IdUtils.getIncreaseIdByNanoTime());
        orgUser.setCreatePsnNo(userInfo.getUserInfoNo());
        orgUser.setCreateTime(DateUtil.now());
        orgUser.setOrgStatusCode(Constant.ORG_STATUS_CODE_01);
        sysOrgUserMapper.insert(orgUser);
        //联系人信息
        T10MemOrgLinkmanInfo memOrgLinkmanInfo = orgUser.getMemOrgLinkmanInfo();
        memOrgLinkmanInfo.setOrgLinkmanNo(IdUtils.getIncreaseIdByNanoTime());//id
        memOrgLinkmanInfo.setOrgUserNo(orgUser.getOrgId());//机构用户编号
        memOrgLinkmanInfo.setUserNo(userInfo.getUserInfoNo());//用户编号
//        memOrgLinkmanInfoTemps.setLinkmanFlag("");//联系人标识
        memOrgLinkmanInfoMapperm.insert(memOrgLinkmanInfo);
        //登录用户信息
        Map<String, Object> userParams = new HashMap<>();
        userParams.put("password",Constant.SET_PASSWD);
        userParams.put("loginName",orgUser.getLoginName());
        //创建机构用户
        SysUserInfo sysUserInfo = new SysUserInfo();
        sysUserInfo.setUserName(orgUser.getOrgName());//用户名
        sysUserInfo.setUserInfoNo(IdUtils.getIncreaseIdByNanoTime());//id
        sysUserInfo.setOrgUserNo(orgUser.getOrgId());//机构用户信息id
        sysUserInfo.setCreateUserNo(userInfo.getUserInfoNo());//创建人
        sysUserInfo.setUserName(orgUser.getOrgName());
        sysUserInfo.setCreateTime(DateUtil.now());//创建时间
        sysUserInfo.setRegIp(InetAddress.getLocalHost().getHostAddress());//ip
        sysUserInfo.setLoginName(orgUser.getLoginName());//登录名
        String salt = Sm3Encrypt.getSaltString();
        sysUserInfo.setUserState(Constant.USER_STATUS_CODE_0);//用户状态
        sysUserInfo.setSalt(salt);
        // 新密码
        String newPassword =Sm3Encrypt.encrypt(salt, (String)userParams.get("password"), (String)userParams.get("loginName"));
        System.out.println("=========================================================================");
        System.out.println("==========================="+newPassword+"===============================");
        System.out.println("=========================================================================");
        sysUserInfo.setPwd(newPassword);//初始密码
        sysUserInfo.setUserType(Constant.USER_TYPE_CODE_02);//机构用户类型
        auUserMapper.insert(sysUserInfo);
        //新增角色关联
        List<Map<String, String>> auUserRoleList = orgUser.getAuUserRoleList();
        if (auUserRoleList.size()>0){
            for (Map<String, String> arId : auUserRoleList) {
                AuUserRole auUserRole = new AuUserRole();
                auUserRole.setAurId(IdUtils.getIncreaseIdByNanoTime());//id
                auUserRole.setAuId(sysUserInfo.getUserInfoNo());//用户编号
                auUserRole.setArId(arId.get("arId"));//角色编号
                auUserRole.setAurCreateUser(userInfo.getUserInfoNo());//创建人
                auUserRole.setAurCreateTime(DateUtil.now());//创建时间
                auUserRole.setAurType(Constant.USER_TYPE_CODE_02);//个人用户类型
                auUserRoleMapper.insert(auUserRole);
            }
        }
        //会员联系人
        MemLinkmanInfo memLinkmanInfo = new MemLinkmanInfo();
        memLinkmanInfo.setInfoInputPsnNo(userInfo.getUserInfoNo());
        memLinkmanInfo.setInfoInputTime(DateUtil.now());
        memLinkmanInfo.setInfsubAuditStatusCode(Constant.INF_SUB_AUDIT_STATUS_CODE_01);
        memLinkmanInfo.setIsCloseStatus(Constant.DELETE_STATUS_CODE_0);
        memLinkmanInfo.setOrgUserNo(orgUser.getOrgId());
        memLinkmanInfo.setLinkmanTypeCode("1");
        //输入
        memLinkmanInfo.setMemLinkmanInfoNo(memOrgLinkmanInfo.getOrgLinkmanNo());
        memLinkmanInfo.setLinkmanName(memOrgLinkmanInfo.getLinkmanName());//联系人名称
        memLinkmanInfo.setLinkmanDutyName(memOrgLinkmanInfo.getLinkmanDutyName());//联系人职务
        memLinkmanInfo.setLinkmanDeptName(memOrgLinkmanInfo.getOrgDepName());//联系人部门名称
        memLinkmanInfo.setLinkmanTel(memOrgLinkmanInfo.getLinkmanOfficeTel());//办公电话
        memLinkmanInfo.setLinkmanMob(memOrgLinkmanInfo.getLinkmanMob());//移动电话
        memLinkmanInfo.setLinkmanFax(memOrgLinkmanInfo.getLinkmanFax());//邮编
        memLinkmanInfo.setLinkmanEml(memOrgLinkmanInfo.getLinkmanEml());//邮箱
        memLinkmanInfo.setLinkmanContactAddr(memOrgLinkmanInfo.getLinkmanContactAddr());//通讯地址
        auUserRoleMapper.insertMemLinkmanInfo(memLinkmanInfo);

        SysUserInfo oginUser = UserUtil.getUserInfo(request);
        String code = oginUser!=null && oginUser.getCode()!=null?oginUser.getCode().trim():null;
        String access_token = oginUser!=null && oginUser.getAccess_token()!=null?oginUser.getAccess_token().trim():null;
        if(code!=null && !code.equals("")){
            if(Client_id!=null && !Client_id.equals("")){
                System.out.println("====推送门户开始====");
                String[] subSystems = new String[]{subSystem1,subSystem2};
                int userType = 2;//用户类型
                System.out.println("orgUser:" + orgUser.toString());
                String orgName = orgUser.getOrgName() == null || StringUtils.isEmpty(orgUser.getOrgName().trim())?null:orgUser.getOrgName().trim();
                String orgCode = orgUser.getAoiOrgNo()== null || StringUtils.isEmpty(orgUser.getAoiOrgNo().trim())?null:orgUser.getAoiOrgNo().trim();
                String member = orgUser.getOrgCode() == null || StringUtils.isEmpty(orgUser.getOrgCode().trim())?null:orgUser.getOrgCode().trim();

                System.out.println("memOrgLinkmanInfo:" + memOrgLinkmanInfo.toString());
                String realName = memOrgLinkmanInfo.getLinkmanName() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getLinkmanName().trim())?null:memOrgLinkmanInfo.getLinkmanName().trim();
                String cartType = memOrgLinkmanInfo.getDtcId() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getDtcId().trim())?null:memOrgLinkmanInfo.getDtcId().trim();
                String cartNo = memOrgLinkmanInfo.getDocumentNo() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getDocumentNo().trim())?null:memOrgLinkmanInfo.getDocumentNo().trim();
                String phone = memOrgLinkmanInfo.getLinkmanMob() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getLinkmanMob().trim())?null:memOrgLinkmanInfo.getLinkmanMob().trim();
                String email = memOrgLinkmanInfo.getLinkmanEml() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getLinkmanEml().trim())?null:memOrgLinkmanInfo.getLinkmanEml().trim();

                System.out.println("orgUser.getOrgAttrCode():" + orgUser.getOrgAttrCode());
                if(orgUser.getOrgAttrCode().equals("04")){
                    subSystems = new String[]{subSystem1};
                }
                PlatformOrgRegVo reg = new PlatformOrgRegVo();
                reg.setAccess_token(access_token);
                reg.setSubSystems(subSystems);
                reg.setOrgName(orgName);
                reg.setOrgCode(orgCode);
                reg.setMember(member);

                reg.setRealName(realName);
                reg.setCartType(cartType);
                reg.setCartNo(cartNo);
                reg.setPhone(phone);
                reg.setEmail(email);

                System.out.println("reg:" + reg.toString());
                ResultDo obj = ssoApiService.PlatformOrgReg(reg);
                out.setMsg(obj.getMsg());
                out.setCode(obj.getCode());
                out.setData(ConvertEntityUtil.convertEntityData(obj));
                String userInfoNo = null;
                if(orgUser.getLoginName()!=null){
                    userInfoNo = orgUser.getLoginName().trim();
                }else{
                    throw  new CustomException(500,"与统一登录门户交互异常，loginName is null,请联系协会系统管理员！");
                }
                System.out.println("userInfoNo:" + userInfoNo);
                if(userInfoNo!=null && !"".equals(userInfoNo.trim()) && obj.getCode()==200 ){
                    Object data = obj.getData();
                    Map<String,String> params = JSONObject.parseObject(data+"", Map.class);
                    if(params!=null){
                        String openId = params.get("openId")!=null?(String)params.get("openId"):"";
                        if(!openId.equals("")){
                            t61SysUserInfoMapper.updateByOpenId(userInfoNo,openId);
                        }else{
                            throw  new CustomException(500,"与统一登录门户交互异常,openId is null，请联系协会系统管理员！");
                        }
                    }else{
                        throw  new CustomException(500,"与统一登录门户交互异常，params is null,请联系协会系统管理员！");
                    }
                }else{
                    throw  new CustomException(500,"与统一登录门户交互异常，" + obj.getMsg() + ", 请联系协会系统管理员！");
                }
                System.out.println("====推送门户结束====");
            }
        }
        return out;
    }

    /**
     * 查询机构用户
     * @param orgId
     * @return
     */
    @Override
    public SysOrgUserInfo queryOrgUser(String orgId) {
        SysOrgUserInfo sysOrgUserInfo = sysOrgUserMapper.selectById(orgId);
        HashMap<String, Object> linkmanMap = new HashMap<>();
        linkmanMap.put("org_user_no", orgId);
        List<T10MemOrgLinkmanInfo> memOrgLinkmanInfos = memOrgLinkmanInfoMapperm.selectByMap(linkmanMap);
        if (memOrgLinkmanInfos != null && memOrgLinkmanInfos.size() > 0) {
            sysOrgUserInfo.setMemOrgLinkmanInfo(memOrgLinkmanInfos.get(0));
        }
        //个人用户与角色关联信息
        SysUserInfo sysUserInfo = auUserMapper.selectByOrgId(orgId, sysOrgUserInfo.getLoginName());
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("au_id", sysUserInfo.getUserInfoNo());
        List<AuUserRole> auUserRoles = auUserRoleMapper.selectByAuId(sysUserInfo.getUserInfoNo());
        List<Map<String, String>> auUserRoleList = new ArrayList<>();
        for (AuUserRole auUserRole : auUserRoles) {
            Map<String, String> arId = new HashMap<>();
            arId.put("arId",auUserRole.getArId());
            arId.put("arName",auUserRole.getArName());
            auUserRoleList.add(arId);
        }
        sysOrgUserInfo.setAuUserRoleList(auUserRoleList);

        return sysOrgUserInfo;
    }

    /**
     * 修改机构用户
     * @param orgUser
     * @param userInfo
     * @throws Exception
     */
    @Override
    public DataOutput updateOrgUser(SysOrgUserInfo orgUser,SysUserInfo userInfo,
                                    HttpServletRequest request) throws Exception {
        DataOutput out = DataOutput.success();
        boolean subSsoOrg = false;
        boolean subSsoGly = false;
        SysOrgUserInfo sysOrgUserInfo = null;
        System.out.println("=====判断机构代码（" + orgUser.getOrgCode() + "）是否存在==========");
        sysOrgUserInfo = sysOrgUserMapper.selectOrgByOrgCode(orgUser.getOrgId(),orgUser.getOrgCode());
        if (sysOrgUserInfo != null) {
            out.setCode(-90001);
            out.setMsg("保存失败，机构代码已存在，请重新输入！");
            return out;
        }else{
            sysOrgUserInfo = sysOrgUserMapper.selectOrgByOrgCode(null,orgUser.getOrgCode());
            if (sysOrgUserInfo == null) {
                subSsoOrg = true;
            }
        }
        System.out.println("=====判断统一社会信用代码（" + orgUser.getAoiOrgNo() + "）是否存在==========");
        sysOrgUserInfo = sysOrgUserMapper.selectOrgByAoiOrgNo(orgUser.getOrgId(),orgUser.getAoiOrgNo());
        if (sysOrgUserInfo != null) {
            out.setCode(-90001);
            out.setMsg("保存失败，统一社会信用代码已存在，请重新输入！");
            return out;
        }else {
            sysOrgUserInfo = sysOrgUserMapper.selectOrgByAoiOrgNo(null, orgUser.getAoiOrgNo());
            if (sysOrgUserInfo == null) {
                subSsoOrg = true;
            }
        }
        System.out.println("=====判断会员证书号码（" + orgUser.getOrgCertifNo() + "）是否存在==========");
        sysOrgUserInfo = sysOrgUserMapper.selectOrgByOrgCertifNo(orgUser.getOrgId(),orgUser.getOrgCertifNo());
        if (sysOrgUserInfo != null) {
            out.setCode(-90001);
            out.setMsg("保存失败，会员证书号码已存在，请重新输入！");
            return out;
        }
        orgUser.setUpdatePsnNo(userInfo.getUserInfoNo());
        orgUser.setUpdateTime(DateUtils.dateTimeToDateString(new Date()));
        sysOrgUserMapper.updateById(orgUser);
        System.out.println("=====判断管理员证件信息是否变动==========");
        T10MemOrgLinkmanInfo memOrgLinkmanInfo = new T10MemOrgLinkmanInfo();
        memOrgLinkmanInfo = memOrgLinkmanInfoMapperm.
                selectDocumentNo(orgUser.getOrgId(),orgUser.getMemOrgLinkmanInfo().getDtcId(),orgUser.getMemOrgLinkmanInfo().getDocumentNo());
        if (memOrgLinkmanInfo == null) {
            subSsoGly = true;
        }
        System.out.println("=====机构管理员==========");
        memOrgLinkmanInfo = orgUser.getMemOrgLinkmanInfo();
        memOrgLinkmanInfoMapperm.updateById(memOrgLinkmanInfo);
        System.out.println("=====用户角色关联==========");
        SysUserInfo sysUserInfo = auUserMapper.selectByOrgId(orgUser.getOrgId(), orgUser.getLoginName());
        HashMap<String, Object> map = new HashMap<>();
        map.put("au_id",sysUserInfo.getUserInfoNo());
        System.out.println("=====删除角色关联==========");
        auUserRoleMapper.deleteByMap(map);
        System.out.println("=====增加角色关联==========");
        List<Map<String, String>> auUserRoleList = orgUser.getAuUserRoleList();
        if (auUserRoleList.size()>0){
            for (Map<String, String> arId : auUserRoleList) {
                AuUserRole auUserRole = new AuUserRole();
                auUserRole.setAurId(IdUtils.getIncreaseIdByNanoTime());//id
                auUserRole.setAuId(sysUserInfo.getUserInfoNo());//用户编号
                auUserRole.setArId(arId.get("arId"));//角色编号
                auUserRole.setAurCreateUser(userInfo.getUserInfoNo());//创建人
                auUserRole.setAurCreateTime(DateUtil.now());//创建时间
                auUserRole.setAurType(Constant.USER_TYPE_CODE_02);//个人用户类型
                auUserRoleMapper.insert(auUserRole);
            }
        }
        System.out.println("=====会员联系人==========");
        MemLinkmanInfo memLinkmanInfo = new MemLinkmanInfo();
        memLinkmanInfo.setInfoInputPsnNo(userInfo.getUserInfoNo());
        memLinkmanInfo.setInfoInputTime(DateUtil.now());
        memLinkmanInfo.setInfsubAuditStatusCode(Constant.INF_SUB_AUDIT_STATUS_CODE_01);
        memLinkmanInfo.setIsCloseStatus(Constant.DELETE_STATUS_CODE_0);
        memLinkmanInfo.setOrgUserNo(orgUser.getOrgId());
        memLinkmanInfo.setLinkmanTypeCode("1");
        //输入
        memLinkmanInfo.setMemLinkmanInfoNo(memOrgLinkmanInfo.getOrgLinkmanNo());
        memLinkmanInfo.setLinkmanName(memOrgLinkmanInfo.getLinkmanName());//联系人名称
        memLinkmanInfo.setLinkmanDutyName(memOrgLinkmanInfo.getLinkmanDutyName());//联系人职务
        memLinkmanInfo.setLinkmanDeptName(memOrgLinkmanInfo.getOrgDepName());//联系人部门名称
        memLinkmanInfo.setLinkmanTel(memOrgLinkmanInfo.getLinkmanOfficeTel());//办公电话
        memLinkmanInfo.setLinkmanMob(memOrgLinkmanInfo.getLinkmanMob());//移动电话
        memLinkmanInfo.setLinkmanFax(memOrgLinkmanInfo.getLinkmanFax());//邮编
        memLinkmanInfo.setLinkmanEml(memOrgLinkmanInfo.getLinkmanEml());//邮箱
        memLinkmanInfo.setLinkmanContactAddr(memOrgLinkmanInfo.getLinkmanContactAddr());//通讯地址
        memLinkmanInfo.setInfoUpdateTime(DateUtil.now());
        memLinkmanInfo.setInfoUpdatePsnNo(userInfo.getUserInfoNo());
        MemLinkmanInfo memLinkmanInfoById = auUserRoleMapper.selectMemLinkmanInfoById(memOrgLinkmanInfo.getOrgLinkmanNo());
        if (memLinkmanInfoById == null) {
            auUserRoleMapper.insertMemLinkmanInfo(memLinkmanInfo);
        }else {
            auUserRoleMapper.updateMemLinkmanInfoById(memLinkmanInfo);
        }
        SysUserInfo oginUser = UserUtil.getUserInfo(request);
        String code = oginUser!=null && oginUser.getCode()!=null?oginUser.getCode().trim():null;
        String access_token = oginUser!=null && oginUser.getAccess_token()!=null?oginUser.getAccess_token().trim():null;
        if(code!=null && !code.equals("")){
            if(Client_id!=null && !Client_id.equals("")){
                System.out.println("====推送门户开始====");
                String[] subSystems = new String[]{subSystem1,subSystem2};
                int userType = 2;//用户类型
                System.out.println("orgUser:" + orgUser.toString());
                String orgName = orgUser.getOrgName() == null || StringUtils.isEmpty(orgUser.getOrgName().trim())?null:orgUser.getOrgName().trim();
                String orgCode = orgUser.getAoiOrgNo()== null || StringUtils.isEmpty(orgUser.getAoiOrgNo().trim())?null:orgUser.getAoiOrgNo().trim();
                String member = orgUser.getOrgCode() == null || StringUtils.isEmpty(orgUser.getOrgCode().trim())?null:orgUser.getOrgCode().trim();
                String openId = orgUser.getOpenId() == null || StringUtils.isEmpty(orgUser.getOpenId().trim())?null:orgUser.getOpenId().trim();

                System.out.println("memOrgLinkmanInfo:" + memOrgLinkmanInfo.toString());
                String realName = memOrgLinkmanInfo.getLinkmanName() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getLinkmanName().trim())?null:memOrgLinkmanInfo.getLinkmanName().trim();
                String cartType = memOrgLinkmanInfo.getDtcId() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getDtcId().trim())?null:memOrgLinkmanInfo.getDtcId().trim();
                String cartNo = memOrgLinkmanInfo.getDocumentNo() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getDocumentNo().trim())?null:memOrgLinkmanInfo.getDocumentNo().trim();
                String phone = memOrgLinkmanInfo.getLinkmanMob() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getLinkmanMob().trim())?null:memOrgLinkmanInfo.getLinkmanMob().trim();
                String email = memOrgLinkmanInfo.getLinkmanEml() == null || StringUtils.isEmpty(memOrgLinkmanInfo.getLinkmanEml().trim())?null:memOrgLinkmanInfo.getLinkmanEml().trim();

                System.out.println("orgUser.getOrgAttrCode():" + orgUser.getOrgAttrCode());
                if(orgUser.getOrgAttrCode().equals("04")){
                    subSystems = new String[]{subSystem1};
                }
                System.out.println("openId: " + openId);
                if(openId!=null){
                    System.out.println("====机构用户修改====");
                    if(subSsoOrg){
                        AccountVo reg = new AccountVo();
                        reg.setAccess_token(access_token);
                        reg.setSubSystems(subSystems);
                        reg.setAppId(Client_id);
                        reg.setUserType(2);
                        reg.setOpenId(openId);
                        reg.setOrgName(orgName);
                        reg.setOrgCode(orgCode);
                        reg.setMember(member);
                        System.out.println("====机构用户信息修改====");
                        ResultDo obj = ssoApiService.AccountOrg(reg);
                        out.setMsg(obj.getMsg());
                        out.setCode(obj.getCode());
                        out.setData(ConvertEntityUtil.convertEntityData(obj));
                        String newOpenId = null;
                        String userInfoNo = null;
                        if(orgUser.getLoginName()!=null){
                            userInfoNo = orgUser.getLoginName();
                        }
                        if(userInfoNo!=null && !"".equals(userInfoNo.trim()) && obj.getCode()==200 ){
                            Object data = obj.getData();
                            Map<String,String> params = JSONObject.parseObject(data+"", Map.class);
                            if(params!=null){
                                openId = params.get("openId")!=null?(String)params.get("openId"):"";
                                newOpenId = params.get("newOpenId")!=null?(String)params.get("newOpenId"):"";
                                if(newOpenId.trim().equals("") && openId.equals(newOpenId)){
                                    t61SysUserInfoMapper.updateByOpenId(userInfoNo,newOpenId);
                                }
                            }else{
                                out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                out.setMsg("与统一登录门户交互异常，请联系协会系统管理员！");
                                throw new CustomException(out.getCode(), out.getMsg());
                            }
                        }else{
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("与统一登录门户交互异常，请联系协会系统管理员！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                    }
                    if(subSsoGly){
                        System.out.println("====机构用户管理员信息修改====");
                        AccountVo reg  = new AccountVo();
                        reg.setAccess_token(access_token);
                        reg.setSubSystems(subSystems);
                        reg.setAppId(Client_id);
                        reg.setUserType(2);
                        reg.setOpenId(openId);
                        reg.setRealName(realName);
                        reg.setCartType(cartType);
                        reg.setCartNo(cartNo);
                        reg.setPhone(phone);
                        reg.setEmail(email);
                        ResultDo obj = ssoApiService.Account(reg);
                        out.setMsg(obj.getMsg());
                        out.setCode(obj.getCode());
                        out.setData(ConvertEntityUtil.convertEntityData(obj));
                        String newOpenId = null;
                        String userInfoNo = null;
                        if(orgUser.getLoginName()!=null){
                            userInfoNo = orgUser.getLoginName();
                        }
                        if(userInfoNo!=null && !"".equals(userInfoNo.trim()) && obj.getCode()==200 ){
                            Object data = obj.getData();
                            Map<String,String> params = JSONObject.parseObject(data+"", Map.class);
                            if(params!=null){
                                openId = params.get("openId")!=null?(String)params.get("openId"):"";
                                newOpenId = params.get("newOpenId")!=null?(String)params.get("newOpenId"):"";
                                if(newOpenId.trim().equals("") && openId.equals(newOpenId)){
                                    t61SysUserInfoMapper.updateByOpenId(userInfoNo,newOpenId);
                                }
                            }else{
                                out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                out.setMsg("与统一登录门户交互异常，请联系协会系统管理员！");
                                throw new CustomException(out.getCode(), out.getMsg());
                            }
                        }else{
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("与统一登录门户交互异常，请联系协会系统管理员！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                    }
                }else{
                    System.out.println("====机构用户新增====");
                    PlatformOrgRegVo reg = new PlatformOrgRegVo();
                    reg.setAccess_token(access_token);
                    reg.setSubSystems(subSystems);
                    reg.setOrgName(orgName);
                    reg.setOrgCode(orgCode);
                    reg.setMember(member);

                    reg.setRealName(realName);
                    reg.setCartType(cartType);
                    reg.setCartNo(cartNo);
                    reg.setPhone(phone);
                    reg.setEmail(email);

                    System.out.println("reg:" + reg.toString());
                    ResultDo obj = ssoApiService.PlatformOrgReg(reg);
                    out.setMsg(obj.getMsg());
                    out.setCode(obj.getCode());
                    out.setData(ConvertEntityUtil.convertEntityData(obj));
                    String userInfoNo = null;
                    if(orgUser.getLoginName()!=null){
                        userInfoNo = orgUser.getLoginName().trim();
                    }else{
                        out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        out.setMsg("与统一登录门户交互异常，loginName is null,请联系协会系统管理员！");
                        throw new CustomException(out.getCode(), out.getMsg());
                    }
                    System.out.println("userInfoNo:" + userInfoNo);
                    if(userInfoNo!=null && !"".equals(userInfoNo.trim()) && obj.getCode()==200 ){
                        Object data = obj.getData();
                        Map<String,String> params = JSONObject.parseObject(data+"", Map.class);
                        if(params!=null){
                            openId = params.get("openId")!=null?(String)params.get("openId"):"";
                            if(!openId.equals("")){
                                t61SysUserInfoMapper.updateByOpenId(userInfoNo,openId);
                            }else{
                                out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                out.setMsg("与统一登录门户交互异常,openId is null，请联系协会系统管理员！");
                                throw new CustomException(out.getCode(), out.getMsg());
                            }
                        }else{
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("与统一登录门户交互异常，params is null,请联系协会系统管理员！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                    }else{
                        out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        out.setMsg("与统一登录门户交互异常，" + obj.getMsg() + ", 请联系协会系统管理员！");
                        throw new CustomException(out.getCode(), out.getMsg());
                    }

                }
                System.out.println("====推送门户结束====");
            }
        }
        return out;
    }

    /**
     * 查询机构用户列表
     * @param input
     * @return
     * @throws Exception
     */
    @Override
    public List<SysOrgUserInfo> queryOrgUserList(DataInput input) throws Exception {
            PageHelper.startPage(input.getPageNum(), input.getPageSize());
        return sysOrgUserMapper.selectAll(input.getParam());
    }

    /**
     * 查询机构用户列表
     * @param input
     * @return
     * @throws Exception
     */
    @Override
    public List<SysUserInfo> queryOrgUserAddRoleList(DataInput input) throws Exception {
        PageHelper.startPage(input.getPageNum(), input.getPageSize());
        return auUserMapper.selectOrgUserList(input.getParam());
    }

    /**
     * 根据角色Id查询机构用户
     * @param input
     * @return
     * @throws Exception
     */
    @Override
    public List<SysUserInfo> queryOrgUserRoleList(DataInput input) throws Exception {
        PageHelper.startPage(input.getPageNum(), input.getPageSize());
        return auUserMapper.selectRoleOrgUserList(input.getParam());
    }
}
